package cn.crap.utils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Properties;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;

public class M1Util {
	
	
	private static Properties properties = new Properties();
	//配置文件名称
	private static final String conifgName = "/m1.properties";
	private static M1Util instance;

	/**
	 * 构造方法 加载配置文件
	 */
	private M1Util() {
		try {
			properties.load(getClass().getResourceAsStream(conifgName));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取单例对象
	 * @return EmpConfig
	 */
	private synchronized static M1Util getInstance() {
		if (null == instance) {
			instance = new M1Util();
		}
		return instance;
	}
	
	
	/**
	 * 将属性值获取为String型
	 * @param str 属性名
	 * @return
	 */
	public static String getString( String str){
		try {
			if (null == instance) {
				getInstance();
			}
			return properties.getProperty( str );
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public static String packageM1(String psm) throws Exception{
		String[] params = psm.split("&");
		String uuid = "";
		TreeMap<String, String> paramMap = new TreeMap<String, String>();
		for(int i = 0; i < params.length ; i++){
			String param = params[i];
			String[] keys = param.split("=");
			if(keys.length==2){
				String key = keys[0];
				String value = keys[1];
				if("uuid".equals(key)){
					uuid = value;
				}else{
					paramMap.put(key, value);
				}
			}
		}
		uuid = StringUtils.isBlank(uuid)?getString("m1_uuid"):uuid;
		TreeMap<String, String> map = new TreeMap<String, String>();
  		map.put("appid", getString("m1_appid"));
  		map.put("apptype", getString("m1_apptype"));
  		map.put("pf", getString("m1_pf"));
  		map.put("v", getString("m1_v"));
  		map.put("vv", getString("m1_vv"));
  		map.put("uuid", uuid);
  		map.put("time", String.valueOf(new Date().getTime()));
  		map.put("time", String.valueOf(new Date().getTime()));
  		StringBuffer sb = new StringBuffer();
		sb.append("appid=").append(map.get("appid")).append("&");
		if(StringUtils.isNotBlank(paramMap.get("token")))sb.append("token=").append(paramMap.get("token")).append("&");
		sb.append("apptype=").append(map.get("apptype")).append("&");
		sb.append("pf=").append(map.get("pf")).append("&");
		sb.append("v=").append(map.get("v")).append("&");
		sb.append("vv=").append(map.get("vv")).append("&");
		sb.append("uuid=").append(uuid).append("&");
		sb.append("time=").append(String.valueOf(new Date().getTime()));
  	    String m1 = Md5Utils.getMd5(sb.toString());
  	    System.out.println("md5 after:"+m1);
  	    psm += "&"+sb+"&m1="+m1;
  	    System.out.println("all prm :"+psm);
		String key = getString("m1_appkey");
		String cipher = AESUtil.encrypt(key,psm); 
		System.out.println("cipher:"+cipher);
		return URLEncoder.encode(cipher, "UTF-8");
	}
}
